package com.xunji.xunji.db.dao;

import android.content.Context;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.xunji.xunji.db.DatabaseHelper;
import com.xunji.xunji.module.trace.dao.Trace;
import com.xunji.xunji.module.trace.dao.TraceImage;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Paul on 2017/2/14.
 */

public class TraceImageDao {
    private Dao<TraceImage, Integer> dao;


    public TraceImageDao(Context context) {
        DatabaseHelper dbHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
        try {
            dao = dbHelper.getDao(TraceImage.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 保存一条用户信息
    public void saveTraceImage(TraceImage bean) {
        try {
            // 如果表中没有该用户则保存，根据主键是否相同来标示是否是同一用户
            dao.createIfNotExists(bean);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //根据id获取用户信息
    public TraceImage getTraceImageById(int id) {
        try {
            return dao.queryForId(id);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<TraceImage> getListByTraceId(int traceId) {
        try {
            return dao.queryBuilder().where().eq("traceId", traceId).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    public TraceImage getTraceByPosition(double lat, double lon) {
        try {
            List<TraceImage> list = dao.queryBuilder().where().eq("longitude", lon).and().eq("latitude", lat).query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }


    public void delete(int id) {
        try {
            dao.deleteById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void update(TraceImage image) {
        try {
            dao.update(image);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
